package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "员工接口")
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 处理登陆请求
     */
    @ApiOperation("处理登陆请求")
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        // 1. 对密码进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        // 2. 根据员工的姓名查询数据
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(queryWrapper);

        // 3. 校验是数据是否为空
        if (null == one) {
            // 数据位空，登陆失败
            log.info("用户名或密码错误");
            return R.error("用户名或密码错误!");
        }

        // 4. 校验密码是否正确
        if (!password.equals(one.getPassword())) {
            // 密码错误，返回错误信息
            log.info("用户名或密码错误");
            return R.error("用户名或密码错误!");
        }

        // 5. 校验用户的状态是否正确
        if (0 == one.getStatus()) {
            // 用户的状态错误
            log.info("用户的状态有误，请联系管理员");
            return R.error("用户的状态有误，请联系管理员!");
        }

        // 6. 用户名密码正确，经员工的id存入到session中，并返回正确的结果
        request.getSession().setAttribute("employee",one.getId());

        return R.success(one);
    }


    /**
     * 处理退出登陆的请求
     */
    @ApiOperation("处理退出登陆的请求")
    @PostMapping("/logout")
    public R<Employee> logout(HttpServletRequest request) {
        log.info("处理退出登陆的请求....");
        // 清空session中的数据
        request.getSession().invalidate();
        // 返回成功的结果
        return R.success();
    }


    /**
     * 添加员工信息
     */
    @ApiOperation("添加员工信息")
    @PostMapping
    public R add(HttpServletRequest request, @RequestBody Employee employee) {
        // 1. 完善数据信息  默认密码位123456
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//
//        // 创建人和修改人 从session中获取
//        Long userId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(userId);
//        employee.setCreateUser(userId);

        // 2. 执行添加方法
        employeeService.save(employee);

        return R.success();
    }

    /**
     * 分页查询
     */
    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码",dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "name", value = "员工姓名", dataTypeClass = String.class)
    })
    @GetMapping("/page")
    public R<Page<Employee>> findPage(@RequestParam(required = false,defaultValue = "1") int page,
                                      @RequestParam(required = false,defaultValue = "5") int pageSize,
                                      String name) {

        //1. 配置分页查询参数
        Page<Employee> pageInfo = new Page<>(page,pageSize);

        //2. 配置条件查询
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        //3. 执行分页查询  // 查询的结果 会将数据封装到传入的Page对象中
        employeeService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }


    /**
     * 启用/禁用用户,同时也是修改员工信息的方法
     */
    @ApiOperation("修改员工信息的方法")
    @PutMapping
    public R modify(HttpServletRequest request,@RequestBody Employee employee) {
        // 1. 补全数据，添加修改人和修改时间
//        Long userId = (Long) request.getSession().getAttribute("employee");
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(userId);

        // 2. 修改员工的状态
        employeeService.updateById(employee);

        return R.success();
    }

    /**
     * 修改用户信息页面的数据回显
     */
    @ApiOperation("修改用户信息页面的数据回显")
    @ApiImplicitParam(name = "id", value = "员工id",dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable String id) {
        log.info("用户员工的id查询员工信息....");
        Employee emp = employeeService.getById(id);
        if (emp != null) {
            return R.success(emp);
        }
        return R.error("没有查询到相关的员工信息");
    }
}
